/**
 * @file Utils.cpp
 *
 * @author Alejandro Dario Simi
 * @url http://www.daemonraco.com
 * @date 2011-12-03
 */

#include <Utils.hpp>

#include <unistd.h>
#include <pwd.h>
#include <iostream>
using namespace std;

Utils* Utils::_Instance = NULL;

Utils::Utils() {
	/*
	 * User Information
	 * @{
	 */
	this->_hasUserInformation = false;
	this->_username = "";
	this->_uid = -1;
	/** @} */
}

Utils::~Utils() {
}

string Utils::cleanPath(const string &path) {
	string out = path;

	int pos;
	while((pos = out.find("//")) != string::npos) {
		out.replace(pos, 2, "/");
	}
	if(out.length() > 1 && out.at(out.length() - 1) == '/') {
		out = out.substr(0, out.length() - 1);
	}

	return out;
}

bool Utils::hasUserInformation() {
	return this->_hasUserInformation;
}

void Utils::loadUserInformation() {
	if(!this->hasUserInformation()) {
		struct passwd *data = getpwuid(getuid());

		this->_uid = getuid();
		this->_username = data->pw_name;
		this->_homeDirectory = data->pw_dir;

		this->_hasUserInformation = true;
	}
}

string Utils::homeDirectory() {
	this->loadUserInformation();
	return this->_homeDirectory;
}

uid_t Utils::uid() {
	this->loadUserInformation();
	return this->_uid;
}

string Utils::username() {
	this->loadUserInformation();
	return this->_username;
}
